const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('node:path');
const { execFile } = require('child_process');
const {PYTHON_SCRIPT_PATH, ELECTRON_PATH, HTML_PATH} =  require('./config').PROJECT_PATH
const fs = require('node:fs');
let venvPath = path.join(app.getAppPath(), 'venv', 'Scripts', 'python.exe'); // Windows

let CONFIG;
// 读取配置文件
const loadConfig = () => {
  const configPath = path.join(app.getAppPath(), 'config.json');
  return new Promise((resolve, reject) => {
    fs.readFile(configPath, 'utf8', (err, data) => {
      if (err) {
        reject(err);
        return;
      }
      try {
        CONFIG = JSON.parse(data);
        resolve();
      } catch (parseError) {
        reject(parseError);
      }
    });
  });
}




function createWindow() {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(ELECTRON_PATH, 'preload.js'),
      contextIsolation: true,
      enableRemoteModule: false,
    }
  });

  win.loadFile(path.join(HTML_PATH,'index.html'));
}

app.whenReady().then(()=>{
  loadConfig()
    .then(() => {
      // 配置成功加载，可以创建窗口等
      console.log('Configuration loaded:', CONFIG);
      // 创建窗口等代码...
    })
    .catch(err => {
      console.error('Failed to load configuration:', err);
    });

  createWindow()
});

ipcMain.handle('run-script', (event, scriptName) => {
    return new Promise((resolve, reject) => {
      //const pythonPath = CONFIG.pythonPath; // 或者 'python3'，取决于你的系统配置
      const pythonPath = venvPath
      // const scriptPath = path.join(PYTHON_SCRIPT_PATH, scriptName);
      // scriptPath = path.join(app.getAppPath(), '..', 'py_scripts', scriptName);
      scriptPath = path.join(app.getAppPath(), CONFIG.scriptPath, scriptName)
      // console.log(`Looking for script at: ${scriptPath}`);

      const pythonProcess = execFile(pythonPath, [scriptPath], (error, stdout, stderr) => {
        if (error) {
          reject(stderr);
          return;
        }
        resolve(stdout);
      });
    });
  });
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});